#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <set>
#include "tree.h"

using namespace std;

void outTree(Tree *head, ofstream &fout)
{
    if (!head){ 
        fout << "#"  << " ";
        return;
    }
    fout << head->data << " ";
    outTree(head->left, fout);
    outTree(head->right, fout);
}

void writeTree(Tree *head)
{
    ofstream fout("tree.out");
    outTree(head, fout); 
    fout.close();
}

int convert(string &str)
{
    int ans = 0;
    for (int i = 0; i < str.size(); i++) {
        ans = ans*10 + str[i] - '0';
    }
    return ans;
}

Tree *recoverTree(ifstream &fin)
{
   string ch;
   fin >> ch;
   if (ch == "#") {
       return NULL;
   }
   int num = convert(ch);
   Tree *head = new Tree(num);
   head->left = recoverTree(fin);
   head->right = recoverTree(fin);
   return head;
}

int main(int argc, char **argv)
{
    int input[] = {21,7,5,6,3,2,1,4,6,23,43,54,12,54,8,10,11,35,56};
    //int input[] = {7};
    Tree *root = NULL, *root2 = NULL;
    int result;

    for (int i = 0; i < sizeof(input)/sizeof(int); i++) {
        TreeInsert(root, input[i]);
    }
    writeTree(root);
    print_ascii_tree(root);
    ifstream fin("tree.out");
    Tree *head = recoverTree(fin);
    print_ascii_tree(head);
}
